const config = require('../config.js');
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatShortTime = data => {
  const year = data.split('-')[0];
  const month = data.split('-')[1];
  const day = data.split('-')[2].split(' ')[0];
  const date = year + '/' + month + '/' + day;
  return date
}

const shortTime = data => {
  const year = data.split('-')[0];
  const month = data.split('-')[1];
  const day = data.split('-')[2].split(' ')[0];
  const hour = data.split(' ')[1].split(':')[0];
  const minute = data.split(' ')[1].split(':')[1];
  const date = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
  return date
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const request = (url, type, headerType, data, callBack) => {
  wx.showLoading({
    mask: true,
  })

  // console.log("getApp().globalData.token");
  // console.log(getApp().globalData.token)
  var token = wx.getStorageSync('token');
  // console.log(token)
  let header = {
    // 'Authorization': 'Bearer ' + getApp().globalData.token,
    'Authorization': 'Bearer ' + token,
    'content-type': 'application/json'
  }
  switch (headerType) {
    case 'withoutAuth':
      header = {
        'content-type': 'application/json'
      }
      break;
    case 'formContent':
      header = {
        'Authorization': 'Bearer ' + token,
        'content-type': 'application/x-www-form-urlencoded'
      }
      break;
  }
  wx.request({
    url: config.HTTP_REQUEST_URL + url,
    data: data,
    method: type,
    dataType: 'json',
    header: header,
    success: (res) => {
      wx.hideLoading()
      callBack(res.data)
    },
    fail: (error) => {
      console.log("util.request", error)
      wx.hideNavigationBarLoading()
      wx.hideLoading()
      showTip(error)
    }
  })
}

//显示提示信息
const showTip = (msg) => {
  wx.showToast({
    title: msg,
    duration: 2000,
    icon: "none",
    mask: true
  })
}

const loginPost = (url, type, data, callBack) => {
  wx.showLoading({
    //title: '...',
    mask: true,
  })
  wx.request({
    url: url,
    data: data,
    method: type,
    dataType: 'json',
    header: {
      'Authorization': 'Basic aml6aGktcG1zLW1hcmtldC1taW5pLWFwaTpqaXpoaS1wbXMtbWFya2V0LW1pbmktYXBp',
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: (res) => {
      wx.hideLoading()
      callBack(res.data)
    },
    fail: (error) => {
      wx.hideNavigationBarLoading()
      wx.hideLoading()
      showTip(error)
      wx.clearStorage('token');
    }
  })
}

/**
 * 加法运算，避免数据相加小数点后产生多位数和计算精度损失。
 * 
 * @param num1加数1 | num2加数2
 */
function numAdd(num1, num2) {
  var baseNum, baseNum1, baseNum2;
  try {
    baseNum1 = num1.toString().split(".")[1].length;
  } catch (e) {
    baseNum1 = 0;
  }
  try {
    baseNum2 = num2.toString().split(".")[1].length;
  } catch (e) {
    baseNum2 = 0;
  }
  baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
  return (num1 * baseNum + num2 * baseNum) / baseNum;
};

/**
 * 减法运算，避免数据相减小数点后产生多位数和计算精度损失。
 * 
 * @param num1被减数  |  num2减数
 */
function numSub(num1, num2) {
  var baseNum, baseNum1, baseNum2;
  var precision; // 精度
  try {
    baseNum1 = num1.toString().split(".")[1].length;
  } catch (e) {
    baseNum1 = 0;
  }
  try {
    baseNum2 = num2.toString().split(".")[1].length;
  } catch (e) {
    baseNum2 = 0;
  }
  baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
  precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2;
  return ((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(precision);
};

/**
 * 乘法运算，避免数据相乘小数点后产生多位数和计算精度损失。
 * 
 * @param num1被乘数 | num2乘数
 */
function numMulti(num1, num2) {
  var baseNum = 0;
  try {
    baseNum += num1.toString().split(".")[1].length;
  } catch (e) {}
  try {
    baseNum += num2.toString().split(".")[1].length;
  } catch (e) {}
  return Number(num1.toString().replace(".", "")) * Number(num2.toString().replace(".", "")) / Math.pow(10, baseNum);
};
/**
 * 除法运算，避免数据相除小数点后产生多位数和计算精度损失。
 * 
 * @param num1被除数 | num2除数
 */
function numDiv(num1, num2) {
  let resNum = 0;
  if (parseFloat(num2) == 0) {
    return resNum;
  }
  try {
    resNum = (num1 * 1000).toString().toFixed(0) / (num2 * 1000).toString().toFixed(0);
  } catch (e) {
    resNum = 0;
  }
  return resNum;
};


module.exports = {
  formatTime: formatTime,
  request: request,
  showTip: showTip,
  loginPost: loginPost,
  formatShortTime: formatShortTime,
  shortTime: shortTime,
  MathAdd: numAdd,
  MathSub: numSub,
  MathMui: numMulti,
  MathDiv: numDiv,
}